package com.neu.edu.boonpay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.neu.edu.boonpay.dao.TransactionsDao;
import com.neu.edu.boonpay.pojo.Transactions;
import com.neu.edu.boonpay.pojo.dto.request.CallBackResponsePo;
import com.neu.edu.boonpay.service.TransactionsService;
import com.neu.edu.boonpay.utils.PartyUtil;
import com.neu.edu.boonpay.utils.TransactionIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class TransactionsServiceImpl implements TransactionsService {

    @Autowired
    private TransactionsDao transactionsDao;

    /**
     *
     * @param transactions
     * @return
     */
    @Override
    public String sendTransactions(Transactions transactions) {
        try {
            // 获得一个transId
            // Get a transId
            //String transID = TransactionIDGenerator.generateTransID();

            // 调用 Transaction API
            //  Call Transaction API, temporarily unavailable
            String apiUrl = String.format(
                    "https://api.RechargeExchange.com/Transaction?userid=%s&token=%s&opcode=%s&number=%s&amount=%f&transid=%s",
                    transactions.getUserId(), "token", transactions.getOperator(), transactions.getMobile(), transactions.getAmount(), transactions.getTransid());
            String sendPostRequest = PartyUtil.sendRequest(apiUrl, "POST");
            // Simulation test successful
            /*String sendPostRequest = "{\n" +
                    "        \"status\":\"SUCCESS\",\n" +
                    "        \"message\":\"Recharge Success\",\n" +
                    "        \"transid\":\"34669(transid-Client unique Id)\",\n" +
                    "        \"optransid\":\"MH02565853234(OperatorTransID)\",\n" +
                    "        \"referenceid\":\"1565464(Website Reference TransID)\",        \n" +
                    "        \"number\":\"7990607312\",\n" +
                    "        \"amount\":\"30\",\n" +
                    "        \"balance\":\"1516.30\"\n" +
                    "        }";*/
            JSONObject jsonObject = JSON.parseObject(sendPostRequest);
            Object status = jsonObject.get("status");
            if (status != null) {
                transactions.setStatus((String) status);
            }
            Object message = jsonObject.get("message");

            Object balance = jsonObject.get("balance");

            Object transid = jsonObject.get("transid");
            if (transid != null) {
                transactions.setTransid((String) transid);
            }

            Object optransid = jsonObject.get("optransid");
            if (optransid != null) {
                transactions.setOptransid((String) optransid);
            }
            // 生成一个用于查询的id
            String referenceid = TransactionIDGenerator.generateTransID();
            transactions.setOptransid(referenceid);
            // 存入数据库
            // Store in the database
            transactionsDao.insert(transactions);
            return sendPostRequest;
        }catch (Exception e){
            log.error("error message =" , e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 	Note : Please check Transaction Status after 5 min otherwise We Block this facility from your Account.
     * 	          Please check Transaction Status once in 5 min otherwise We Block this facility from your Account.
     * 	       While StatusCheck You got Pending In Response Then You have to Check Status Again For That Transaction.
     *
     * 	Fail Case : if Transaction goes Pending To Fail Then we Automatically Refund Amount
     * 			in Your Account and Transaction Status goes in Refund at website.
     * @param userid
     * @param token
     * @param transid
     * @return
     */
    @Override
    public String getTransactionStatus(Integer userid, String token, String transid) {
        try {
            String apiUrl = String.format(
                    "https://status.rechargeexchange.com/API.asmx/TransactionStatus?userid=%s&token=%s&transid=%s",
                    userid, token, transid);
            String transactionStatus = PartyUtil.sendRequest(apiUrl, "POST");
            return transactionStatus;
        }catch (Exception e){
            log.error("error message =" , e.getMessage());
            e.printStackTrace();
        }

        return "";
    }

    /**
     * Note :
     * 1)We Send CallBack Response In GET Format Only.
     * 2)We Only Give CallBack Response For Status Pending To Success,Fail
     * 3)We Can't Give CallBack Response For Direct Success,Fail Response.
     * 注：
     *
     * 1） 我们仅以GET格式发送回叫响应。
     *
     * 2） 我们只对等待成功、失败的状态给予回拨响应
     *
     * 3） 我们不能为直接成功或失败的响应提供回拨响应。
     * @param callBackResponsePo
     * @return
     */
    @Override
    public String callBackResponse(CallBackResponsePo callBackResponsePo) {
        try{
            String apiUrl = String.format(
                    "https://www.yourdomain.com/callback?status=%s&opid=%s&yourtransid=%s&txnid=%s&number=%s&amount=%s&message=%s",
                    callBackResponsePo.getStatus(), callBackResponsePo.getOpid(), callBackResponsePo.getYourtransid(), callBackResponsePo.getTxnid(), callBackResponsePo.getNumber(), callBackResponsePo.getAmount(), callBackResponsePo.getMessage());
            String sendGetRequest = PartyUtil.sendRequest(apiUrl, "GET");
            QueryWrapper<Transactions> queryWrapper = new QueryWrapper();
            JSONObject jsonObject = JSON.parseObject(sendGetRequest);
            Object optransid = jsonObject.get("optransid");
            if (optransid != null) {
                queryWrapper.eq("optransid",optransid.toString());
            }

            Transactions transactions = new Transactions();
            transactions.setTransid(callBackResponsePo.getYourtransid());

            transactionsDao.update(transactions, queryWrapper);
            return sendGetRequest;
        }catch (Exception e){
            log.error("error message =" , e.getMessage());
            e.printStackTrace();
        }
        return "";
    }


}
